#ifdef WX_PRECOMP
#include "wx_pch.h"
#else
#include <wx/wx.h>
#endif //WX_PRECOMP

#include "export_design_script.h"
#include "lua_output_wrapper.h"
#include "lua_unit_info_wrapper.h"
#include "string_conv.h"

extern "C" {
  #include <lua.h>
  #include <lauxlib.h>
  #include <lualib.h>
}

ExportDesignScript::ExportDesignScript(const Design& design, int raceID)
  : Machine(lua_open())
{
  luaopen_base(Machine);
  luaopen_table(Machine);
  luaopen_string(Machine);
  luaopen_math(Machine);

  OutputStream = CreateLuaOutputWrapper(Machine);
  UnitInfo = CreateLuaUnitInfoWrapper(Machine, "Unit", design, raceID);
}

ExportDesignScript::~ExportDesignScript()
{
  lua_close(Machine);
}

wxString ExportDesignScript::Process(const wxString& script)
{
  const wxCharBuffer buffer = wx2lua(script);
  luaL_dostring(Machine, buffer.data());

  const std::string out = OutputStream->GetResult();
  const wxString result(out);

  OutputStream->Clear();
  return result;
}
